package com.chat.net.socket;

import com.chat.entity.DataPackage;
import com.chat.net.SocketClient;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.LinkedList;

public class ObjectChannelContext extends SocketChannelContext implements Runnable {

    ObjectInputStream objectInputStream;
    ObjectOutputStream objectOutputStream;

    LinkedList<DataPackage> dataPackages;

    public ObjectChannelContext(Socket socket) throws IOException {
        super(socket);
        dataPackages = new LinkedList<>();
    }

    public Object readObject() {
        if (dataPackages.size() > 0)
            return dataPackages.poll();
        else
            return null;
    }

    public void writeObject(Object object) throws IOException {
        SocketClient.getSocketClient().getExecutor().execute(new Runnable() {
            @Override
            public void run() {
                if (object != null) {
                    try {
                        objectOutputStream.writeObject(object);
                        objectOutputStream.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @Override
    public void run() {
        try {
            objectOutputStream = new ObjectOutputStream(outputStream);
            objectInputStream = new ObjectInputStream(inputStream);
            while (true) {
                DataPackage dataPackage = (DataPackage) objectInputStream.readObject();
                if (dataPackage != null) {
                    dataPackages.push(dataPackage);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}